<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        #canvas{
            display: block;
        }
    </style>
</head>
<body>
    
    <canvas id="canvas" width="100" height="100"></canvas>

    <script>
        let canvas=document.getElementById('canvas')
        let ctx=canvas.getContext("2d");
        
        canvas.width= document.documentElement.clientWidth;
        canvas.height=document.documentElement.clientHeight;
        ctx.fillStyle = 'black';
        ctx.lineWidth=10;
        ctx.lineCap="round"
        ctx.font = "30px serif";
        ctx.fillText("你可以在画板上涂鸦", 10, 50);
       
        let panting =false;
        let lastXY=[];
        let isTouchDevice='ontouchstart' in document.documentElement;

        if(isTouchDevice){
            console.log("isTouchDevice======"+isTouchDevice);
            canvas.ontouchmove=(e)=>{
                let x=e.touches[0].clientX;
                let y=e.touches[0].clientY;
                ctx.beginPath();
                ctx.arc(x,y,10,0,2*Math.PI)
                ctx.stroke();
                ctx.fill();
            }
        }else{
            canvas.onmousedown=(e)=>{
                panting=true;
                 // 获取鼠标弹起时的坐标
                lastXY=[e.clientX, e.clientY]
            }
            canvas.onmousemove=(e)=>{
                if(panting===true){
                   
                    dragline(lastXY[0],lastXY[1],e.clientX, e.clientY,)
                    lastXY=[e.clientX, e.clientY] //更新鼠标弹起的坐标
                }else{
                    console.log("什么都不画");
                }
            }
            canvas.onmouseup=()=>{
                panting=false;
            }
        }

        //画一条线的函数
         function dragline(x1,y1,x2,y2){
            ctx.beginPath();
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.stroke();
        }

    </script>
    
</body>
</html>